﻿#include "date_edit.h"
#include "date_widget.h"

#include <QTableWidget>
#include <QHeaderView>
#include <QDateTime>
#include <QDebug>

DateEdit::DateEdit(QWidget *parent) : QComboBox(parent)
{
	initPage();
}

void DateEdit::initPage()
{
    auto table = new QTableWidget;
    table->setMinimumHeight(378);
    table->setMinimumWidth(300);
    table->verticalHeader()->setVisible(false);
    table->horizontalHeader()->setVisible(false);
    table->setColumnCount(1);
    table->setRowCount(1);
    table->setRowHeight(0,10);

    cell = new DateWidget(this);
    cell->setMinimumHeight(378);
    cell->setMinimumWidth(this->width() > 300 ? this->width() : 300);
    table->setCellWidget(0, 0, cell);

    this->setModel(table->model());
    this->setView(table);
    this->setProperty("type", "datetime");

    this->setEditable(true);

    connect(cell, static_cast<void(DateWidget::*)(const QDate&)>(&DateWidget::signal_date), this, [this](const QDate& dt)
    {
        this->setEditText(dt.toString("yyyy-MM-dd"));
        this->hidePopup();
    });

    connect(cell, &DateWidget::signal_cancel, this, [this]
    {
        hidePopup();
    });
}

void DateEdit::mousePressEvent(QMouseEvent *e)
{
    cell->setMinimumWidth(this->width()>300 ? this->width():300);
    cell->update();
    showPopup();
}


void DateEdit::setDate(const QDate& dt)
{
    this->setEditText(dt.toString("yyyy-MM-dd"));

	auto pTable = static_cast<QTableWidget*>(const_cast<QAbstractItemView*>(view()));
    auto pWidget = static_cast<DateWidget*>(pTable->cellWidget(0, 0));

    pWidget->setDate(dt);
}

QString DateEdit::dateToStr()
{
    QString str=this->currentText().mid(0,10);

    return str;
}

QDate DateEdit::date() const
{
    return QDate::fromString(this->currentText(), "yyyy-MM-dd");
}
